package com.tttshaoqi.server.service.impl;

import com.tttshaoqi.common.constant.RedisConstants;
import com.tttshaoqi.common.result.Result;
import com.tttshaoqi.common.utils.EmpHolder;
import com.tttshaoqi.pojo.dto.EmployeeDTO;
import com.tttshaoqi.server.mapper.UserMapper;
import com.tttshaoqi.pojo.entity.User;
import com.tttshaoqi.server.security.JwtUtil;
import com.tttshaoqi.server.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;
    private final StringRedisTemplate  redisTemplate;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Transactional
    @Override
    public User registerByPassword(String username, String phone, String rawPassword) {
        User user = new User()
                .setUsername(username)
                .setPhone(phone)
                .setPasswordHash(passwordEncoder.encode(rawPassword))
                .setNickname(username)
                .setLikedCount(0L)
                .setPostCount(0L)
                .setCreatedAt(LocalDateTime.now())
                .setUpdatedAt(LocalDateTime.now());
        try {
            userMapper.insert(user);
            return user;
        } catch (Exception e) {
            throw new DuplicateKeyException("用户名或手机号已存在");
        }
    }

    @Override
    public String loginByPassword(String account, String rawPassword) {
        User user = Optional.ofNullable(userMapper.findByUsername(account))
                .orElseGet(() -> userMapper.findByPhone(account));
        if (user == null) return null;
        if (!passwordEncoder.matches(rawPassword, user.getPasswordHash())) {
            return null;
        }
        EmployeeDTO employeeDTO = new EmployeeDTO();
        BeanUtils.copyProperties(user,employeeDTO);
        // 将用户信息存入redis
        String token = UUID.randomUUID().toString();
        Map<String,Object> mp = new HashMap<>();
        mp.put("id",""+employeeDTO.getId());
        mp.put("username",employeeDTO.getUsername());
        mp.put("phone",employeeDTO.getPhone());
        redisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,mp);
        // 存储登录信息
        EmpHolder.saveEmp(employeeDTO);
        // 7.4.设置token有效期
        redisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,
                RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        return token;
    }


    @Override
    public Optional<User> findById(Long id) {
        return Optional.ofNullable(userMapper.findById(id));
    }
}



